package cmpp;

import cmpp.pdu.CmppPDU;
import cmpp.pdu.CmppPDUParser;
import cmpp.sms.ByteBuffer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * Created by ddouble on 2017/7/1.
 */
public class CmppDecoder extends ByteToMessageDecoder {
    static protected Logger logger = Logger.getLogger(CmppDecoder.class.getName());

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int length = byteBuf.getInt(byteBuf.readerIndex());
        int readable = byteBuf.readableBytes();
        if (readable >= length) {
            length = byteBuf.readInt();
            byte[] bytedata = new byte[length - 4];
            byteBuf.readBytes(bytedata);
            ByteBuffer buffer = new ByteBuffer();
            buffer.appendInt(length);
            buffer.appendBytes(bytedata);
            CmppPDU pdu = CmppPDUParser.createPDUFromBuffer(buffer);
            if (pdu == null) {
                logger.error("Unknown message");
            } else {
                list.add(pdu);
            }
        }
    }

    //    protected void decode(ChannelHandlerContext ctx, ByteBuf in,
//                          MessageBuf<Object> out) throws Exception {
//        // TODO Auto-generated method stub
//        while (in.readableBytes() >= 4) {
//            out.add(new UnixTime(in.readInt()));
//        }
//    }

}
